package com.whxd.oauth.service;

import com.alibaba.fastjson.JSON;
import com.whxd.oauth.dto.UserDto;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @version 1.0
 **/
@Component
public class SpringDataUserDetailsService implements UserDetailsService {

    private static Map<String, UserDto> userMaps = new HashMap<>();

    static {
        userMaps.put("张三", new UserDto("1", "张三", new BCryptPasswordEncoder().encode("123456"), "", ""));
        userMaps.put("李氏", new UserDto("2", "李氏", new BCryptPasswordEncoder().encode("123456"), "", ""));
    }

    //根据 账号查询用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //模拟根据连接数据库根据账号查询用户信息
        if(!userMaps.containsKey(username)){
            //如果用户查不到，返回null，由provider来抛出异常
            return null;
        }
        UserDto userDto = userMaps.get(username);
        //根据用户的id查询用户的权限
        List<String> permissions = new ArrayList<>();
        permissions.add("p1");
        //将permissions转成数组
        String[] permissionArray = new String[permissions.size()];
        permissions.toArray(permissionArray);
        //将userDto转成json
        String principal = JSON.toJSONString(userDto);
        UserDetails userDetails = User.withUsername(userDto.getUsername()).password(userDto.getPassword()).authorities(permissionArray).build();
        return userDetails;
    }
}
